<script setup lang="ts" name="Template01">
import { user } from '@/api/user'
import { getTimeState } from '@/utils/dateFormat'
import { storeToRefs } from 'pinia'
import { useSystemConfigStore } from '@/store/storage/systemConfigStore'
import { useUserInfoStoreWithOut } from '@/store/storage/userInfoStore'
import { useLoginStoreWithOut } from '@/store/storage/loginStore'
import { throttle } from 'lodash-es'
import { transformI18n } from '@/plugins/i18n'
import { accountRule, emailRule, phoneRule } from '@/utils/formValidate'
const router = useRouter()
const route = useRoute()
const systemConfigStore = useSystemConfigStore()
const { systemConfig } = storeToRefs(systemConfigStore)
const userInfoStore = useUserInfoStoreWithOut()
const { userInfo } = storeToRefs(userInfoStore)
const loginStore = useLoginStoreWithOut()

const loginFormRef = ref(null)
const registerFormRef = ref(null)
const recoverFormRef = ref(null)

const passwordRule = (rule, value, callback) => {
  const reg = /^[a-zA-Z0-9_\-\.]{6,20}$/
  if (!value) {
    callback(new Error(transformI18n('verifies.' + '请输入密码！', true)))
  } else if (!reg.test(value)) {
    callback(new Error(transformI18n('verifies.' + '密码格式错误！', true)))
  } else {
    if (initInfo.value.register.form.passwordConfirm !== '') {
      if (!registerFormRef.value) return
      registerFormRef.value.validateField('passwordConfirm', () => null)
    }
    callback()
  }
}
const passwordConfirmRule = (rule, value, callback) => {
  const reg = /^[a-zA-Z0-9_\-\.]{6,20}$/
  if (!value) {
    callback(new Error(transformI18n('verifies.' + '请再次输入密码！', true)))
  } else if (!reg.test(value)) {
    callback(new Error(transformI18n('verifies.' + '密码格式错误！', true)))
  } else {
    if (initInfo.value.register.form.password !== value) {
      callback(new Error(transformI18n('verifies.' + '两次密码输入不一致！', true)))
    }
    callback()
  }
}

const initInfo = ref({
  type: 'login',
  login: {
    form: {
      account: 'admin',
      password: '123456'
    },
    rules: {
      account: [{ required: true, message: transformI18n('verifies.' + '请输入账号！', true), trigger: 'blur' }],
      password: [{ required: true, message: transformI18n('verifies.' + '请输入密码！', true), trigger: 'blur' }]
    }
  },
  register: {
    form: {
      account: '',
      password: '',
      passwordConfirm: '',
      phone: '',
      email: ''
    },
    rules: {
      account: [{ required: true, validator: accountRule, trigger: 'blur' }],
      password: [{ required: true, validator: passwordRule, trigger: 'blur' }],
      passwordConfirm: [{ required: true, validator: passwordConfirmRule, trigger: 'blur' }],
      phone: [{ required: true, validator: phoneRule, trigger: 'blur' }],
      email: [{ required: true, validator: emailRule, trigger: 'blur' }]
    }
  },
  recover: {
    countdown: 0,
    timer: null,
    isCountdown: false,
    form: {
      email: '',
      phone: '',
      code: ''
    },
    rules: {
      email: [{ required: true, validator: emailRule, trigger: 'blur' }],
      phone: [{ required: true, validator: phoneRule, trigger: 'blur' }],
      code: [{ required: true, message: transformI18n('verifies.' + '请输入验证码！', true), trigger: 'blur' }]
    }
  }
})
// 登录点击事件
const onLogin = () => {
  if (!loginFormRef.value) return false
  loginFormRef.value.validate((valid) => {
    if (valid) {
      user.login(initInfo.value.login.form, { config: { mockEnable: true } }).then((res: any) => {
        if (res && res.status) {
          const { accessToken, refreshToken, data } = res
          data.accessToken = accessToken
          data.refreshToken = refreshToken
          userInfo.value = data
          userInfoStore.setUserInfoCache()
          ElNotification({
            title: transformI18n('text.' + getTimeState(), true),
            message: transformI18n('successes.successLoginInfo', true),
            type: 'success'
          })
          systemConfig.value.isLogin = true
          systemConfig.value.isLockScreen = false
          systemConfigStore.setSystemConfigCache()
          // 如果用户真正访问的页面需要登录权限，在跳转到登陆页用户登陆后，需重新跳转到用户真正要访问的页面
          if (route.query.redirect) {
            router.push({ path: route.query.redirect as string })
          } else {
            router.push({ path: '/' })
          }
        }
      })
    }
  })
}

// 注册事件
const onRegister = () => {
  if (!registerFormRef.value) return false
  registerFormRef.value.validate((valid) => {
    if (valid) {
      user.register(initInfo.value.register.form, { config: { mockEnable: true } }).then((res: any) => {
        if (res && res.status) {
          registerFormRef.value.resetFields()
          initInfo.value.type = 'login'
          ElNotification({
            title: transformI18n('text.注册成功', true),
            message: transformI18n('text.请妥善保管好个人账号，切勿借与他人，并定期修改密码。', true),
            type: 'success',
            duration: 0
          })
        }
      })
    }
  })
}

const changeType = (v) => {
  initInfo.value.type = v
}

const registerHandle = throttle(onRegister, 60 * 1000)

const getCode = () => {
  if (!recoverFormRef.value) return false
  const countdownTime = new Date().getTime() + 1000 * 60
  loginStore.setRecoverCountdownCache(countdownTime)
  recoverFormRef.value.validateField(['email', 'phone'], valid => {
    if (valid) {
      user.code(initInfo.value.recover.form, { config: { mockEnable: true } }).then((res: any) => {
        if (res && res.status) {
          timerCountdown(countdownTime)
        } else {
          loginStore.removeRecoverCountdownCache()
        }
      })
    }
  })
}

const confirmRecover = () => {
  if (!recoverFormRef.value) return false
  recoverFormRef.value.validate((valid) => {
    if (valid) {
      user.recover(initInfo.value.recover.form, { config: { mockEnable: true } }).then((res: any) => {
        if (res && res.status) {
          recoverFormRef.value.resetFields()
          initInfo.value.type = 'login'
          ElNotification({
            title: transformI18n('text.账号已成功找回', true),
            dangerouslyUseHTMLString: true,
            message: '<div class="recover-notification"><div class="item-line"><span>' + transformI18n('text.账号：', true) + '</span><strong>' + res.data.account + '</strong></div><div class="item-line"><span>' + transformI18n('text.密码：', true) + '</span><strong>' + res.data.password + '</strong></div><p>' + transformI18n('text.请妥善保管好个人账号，切勿借与他人，并定期修改密码。', true) + '</p></div>',
            type: 'success',
            duration: 0
          })
        }
      })
    }
  })
}

const timerCountdown = (time) => {
  if (!initInfo.value.recover.timer) {
    initInfo.value.recover.countdown = Math.ceil((JSON.parse(time) - new Date().getTime()) / 1000)
    initInfo.value.recover.isCountdown = true
    initInfo.value.recover.timer = setInterval(() => {
      if (initInfo.value.recover.countdown > 0) {
        initInfo.value.recover.countdown--
      } else {
        initInfo.value.recover.isCountdown = false
        clearInterval(initInfo.value.recover.timer)
        initInfo.value.recover.timer = null
        loginStore.removeRecoverCountdownCache()
      }
    }, 1000)
  }
}

onMounted(() => {
  if (loginStore.getRecoverCountdownCache()) {
    const endTime = loginStore.getRecoverCountdownCache()
    timerCountdown(endTime)
  }
})
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <el-form v-if="initInfo.type === 'login'" ref="loginFormRef" class="login-form" :model="initInfo.login.form" :rules="initInfo.login.rules">
        <p v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 100 } }">
          {{
            $t('text.欢迎登录') }}
        </p>
        <h2 v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 200 } }">
          {{ $t('settings.settingProjectTitle') }}
        </h2>
        <el-form-item prop="account">
          <div class="input-group" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 300 } }">
            <div class="item-icon">
              <el-icon><svg-icon icon="ep:user"></svg-icon></el-icon>
            </div>
            <div class="item-input">
              <el-input type="text" class="input" v-model="initInfo.login.form.account" clearable :placeholder="$t('placeholders.帐号')" @keyup.enter="onLogin" />
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="password">
          <div class="input-group" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 400 } }">
            <div class="item-icon">
              <el-icon><svg-icon icon="ep:lock"></svg-icon></el-icon>
            </div>
            <div class="item-input">
              <el-input type="password" class="input" v-model="initInfo.login.form.password" show-password clearable :placeholder="$t('placeholders.登录密码')" @keyup.enter="onLogin" />
            </div>
          </div>
        </el-form-item>
        <div class="link-wrap" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 500 } }">
          <span @click="changeType('recover')">{{ $t('text.忘记密码？') }}</span>
        </div>
        <el-button class="btn-login" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 600 } }" @click="onLogin">
          {{ $t("buttons.buttonLogin")
          }}
        </el-button>
        <div class="register-wrap" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 700 } }">
          {{ $t('text.还没有账号？') }}
          <span @click="changeType('register')">{{ $t("buttons.点击注册") }}</span>
        </div>
      </el-form>
      <el-form v-else-if="initInfo.type === 'recover'" ref="recoverFormRef" class="login-form" :model="initInfo.recover.form" :rules="initInfo.recover.rules">
        <p class="title" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 100 } }">
          <svg-icon icon="ep:arrow-left" @click="changeType('login')"></svg-icon>
          {{ $t('text.找回密码') }}
        </p>
        <el-form-item prop="email">
          <div class="input-group" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 200 } }">
            <div class="item-icon">
              <el-icon><svg-icon icon="ep:user"></svg-icon></el-icon>
            </div>
            <div class="item-input">
              <el-input type="text" class="input" v-model="initInfo.recover.form.email" clearable :placeholder="$t('placeholders.邮箱')" />
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="phone">
          <div class="input-group" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 300 } }">
            <div class="item-icon">
              <el-icon><svg-icon icon="ep:cellphone"></svg-icon></el-icon>
            </div>
            <div class="item-input">
              <el-input type="text" class="input" v-model="initInfo.recover.form.phone" clearable :placeholder="$t('placeholders.手机号')" />
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="code">
          <div class="input-wrap" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 400 } }">
            <div class="input-group">
              <div class="item-icon">
                <el-icon><svg-icon icon="ri:shield-line"></svg-icon></el-icon>
              </div>
              <div class="item-input">
                <el-input type="text" class="input" v-model="initInfo.recover.form.code" clearable :placeholder="$t('placeholders.验证码')" />
              </div>
            </div>
            <el-button v-if="!initInfo.recover.isCountdown" class="btn-code" type="warning" plain @click="getCode">
              {{
                $t("buttons.获取验证码") }}
            </el-button>
            <el-button v-else class="btn-code" type="warning" plain disabled>
              {{ transformI18n('buttons.{0}秒后重试', true,
                [initInfo.recover.countdown]) }}
            </el-button>
          </div>
        </el-form-item>
        <el-button class="btn-recover" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 500 } }" @click="confirmRecover">
          {{ $t("buttons.确认找回")
          }}
        </el-button>
      </el-form>
      <el-form v-else ref="registerFormRef" class="login-form" :model="initInfo.register.form" :rules="initInfo.register.rules">
        <p class="title" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 100 } }">
          <svg-icon icon="ep:arrow-left" @click="changeType('login')"></svg-icon>
          {{ $t('text.注册') }}
        </p>
        <el-form-item prop="account">
          <el-popover placement="right" width="220" trigger="hover" :content="$t('text.accountRule')" popper-style="font-size: 12px;">
            <template #reference>
              <div class="input-group" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 200 } }">
                <div class="item-icon">
                  <el-icon><svg-icon icon="ep:user"></svg-icon></el-icon>
                </div>
                <div class="item-input">
                  <el-input type="text" class="input" v-model="initInfo.register.form.account" clearable :placeholder="$t('placeholders.帐号')" />
                </div>
              </div>
            </template>
          </el-popover>
        </el-form-item>
        <el-form-item prop="password">
          <el-popover placement="right" width="220" trigger="hover" :content="$t('text.passwordRule')" popper-style="font-size: 12px;">
            <template #reference>
              <div class="input-group" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 300 } }">
                <div class="item-icon">
                  <el-icon><svg-icon icon="ep:unlock"></svg-icon></el-icon>
                </div>
                <div class="item-input">
                  <el-input type="password" class="input" v-model="initInfo.register.form.password" show-password clearable :placeholder="$t('placeholders.密码')" />
                </div>
              </div>
            </template>
          </el-popover>
        </el-form-item>
        <el-form-item prop="passwordConfirm">
          <el-popover placement="right" width="220" trigger="hover" :content="$t('text.passwordRule')" popper-style="font-size: 12px;">
            <template #reference>
              <div class="input-group" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 400 } }">
                <div class="item-icon">
                  <el-icon><svg-icon icon="ep:lock"></svg-icon></el-icon>
                </div>
                <div class="item-input">
                  <el-input type="password" class="input" v-model="initInfo.register.form.passwordConfirm" show-password clearable :placeholder="$t('placeholders.确认密码')" />
                </div>
              </div>
            </template>
          </el-popover>
        </el-form-item>
        <el-form-item prop="phone">
          <div class="input-group" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 500 } }">
            <div class="item-icon">
              <el-icon><svg-icon icon="ep:cellphone"></svg-icon></el-icon>
            </div>
            <div class="item-input">
              <el-input type="text" class="input" v-model="initInfo.register.form.phone" clearable :placeholder="$t('placeholders.手机号')" />
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="email">
          <div class="input-group" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 600 } }">
            <div class="item-icon">
              <el-icon><svg-icon icon="ep:message"></svg-icon></el-icon>
            </div>
            <div class="item-input">
              <el-input type="text" class="input" v-model="initInfo.register.form.email" clearable :placeholder="$t('placeholders.邮箱')" />
            </div>
          </div>
        </el-form-item>
        <el-button class="btn-register" v-motion :initial="{ opacity: 0, y: 10 }" :enter="{ opacity: 1, y: 0, transition: { delay: 700 } }" @click="registerHandle">
          {{ $t("buttons.注册")
          }}
        </el-button>
      </el-form>
    </div>
  </div>
</template>
<style scoped lang="scss">
.login-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100vw;
  min-height: 100vh;
  padding: var(--el-space);
  overflow-y: hidden;
  background-color: #2d3a4b;
  background-image: url('../../../../assets/login/template01/login-bg.png');
  background-repeat: no-repeat;
  background-position: 200px center;
}

.login-img {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.login-box {
  display: flex;
  flex: 0 0 50%;
  align-items: center;
  justify-content: center;
  text-align: center;

  .login-form {
    width: 360px;

    .title {
      display: flex;
      align-items: center;

      .el-icon {
        width: 30px;
        height: 30px;
        font-size: 20px !important;
        cursor: pointer;
      }
    }

    :deep(.el-form-item__content) {
      >.el-form-item__error {
        margin-top: 1px;
      }
    }

    .el-form-item {
      margin: 20px 0;

      &.is-error {
        :deep(.el-input__wrapper) {
          box-shadow: none !important;
        }
      }
    }

    >p {
      color: #ffffff;
      font-size: 20px;
      text-align: left;
    }

    h2 {
      margin: 15px 0;
      color: #ffffff;
      font-weight: bold;
      font-size: 36px;
      text-align: left;
      text-transform: capitalize;
    }

    .el-input {
      padding: 0;
      background: none;
      border: none;

      :deep(.el-input__wrapper) {
        padding: 0;
        background: none;
        border: none;
        box-shadow: none;

        .el-input__inner {
          padding: 0;
          color: #ffffff;
          font-size: 14px;
          background: none;
          border: none;
        }
      }
    }
  }
}

.link-wrap {
  margin-top: -15px;
  text-align: right;

  span {
    color: #9c9fa5;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      color: var(--el-color-primary);
    }
  }
}

.register-wrap {
  color: #9c9fa5;

  span {
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      color: var(--el-color-primary);
    }
  }
}

.input-wrap {
  display: flex;
  flex: 1;

  .input-group {
    margin: 0;
  }

  .item-img {
    display: flex;
    align-items: center;
    height: 42px;
    margin-left: 16px;

    .el-image {
      height: 32px;
    }
  }

  .btn-recover {
    width: auto;
    margin-top: 1px;
    margin-bottom: 1px;
    margin-left: 20px;
    font-size: 14px;
  }
}

.input-group {
  position: relative;
  display: flex;
  flex: 1;
  padding: 5px 0;
  color: #454545;
  background: rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 3px;

  &.focus {

    &::before,
    &::after {
      width: 50%;
    }

    .item-icon {
      color: var(--el-color-primary);
    }

    .item-input {
      h5 {
        top: -5px;
        font-size: 15px;
      }
    }
  }

  .item-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    color: #d9d9d9;
    font-size: 18px;
  }

  .item-input {
    position: relative;
    flex: 1;
    height: 30px;
    padding-right: 15px;

    h5 {
      position: absolute;
      top: 50%;
      left: 10px;
      margin: 0;
      padding: 0;
      color: #d9d9d9;
      font-weight: normal;
      font-size: 16px;
      transform: translateY(-50%);
      transition: 0.3s;
    }

    .el-select {
      display: flex;
      line-height: 30px;

      :deep(.el-input) {
        &.is-focus {
          .el-input__wrapper {
            box-shadow: none !important;
          }
        }
      }

      :deep(.el-input__wrapper) {
        padding: 0;

        &.is-focus {
          box-shadow: none !important;
        }
      }

      :deep(.select-trigger) {
        display: flex;
        flex: 1;

        .el-input__wrapper {
          background-color: transparent;
          box-shadow: none;

          .el-input__inner {
            height: 28px;
            color: #ffffff;
            line-height: 28px;
          }
        }
      }
    }

    .input {
      display: flex;
      width: 100%;
      height: 100%;
      padding: 4px 0;
      color: #ffffff;
      font-size: 16px;
      background: none;
      border: none;
      outline: none;

      &:-webkit-autofill,
      &:-webkit-autofill:hover,
      &:-webkit-autofill:focus,
      &:-webkit-autofill:active {
        transition: color 99999s ease-out 99999s, background-color 99999s ease-out 99999s;
      }
    }
  }
}

.btn-code {
  display: block;
  min-width: 150px;
  height: 40px;
  margin-left: 20px;
  font-size: 16px;
  text-transform: capitalize;
  outline: none;
  cursor: pointer;
  transition: 0.5s;

  &.is-disabled {
    text-transform: none;
  }
}

.btn-login {
  display: block;
  width: 100%;
  height: 40px;
  margin: 1rem 0;
  color: #ffffff;
  font-size: 16px;
  text-transform: capitalize;
  background: linear-gradient(to right, var(--el-color-primary-light-5), var(--el-color-primary), var(--el-color-primary-light-5));
  background-size: 200%;
  border: none;
  border-radius: 4px;
  outline: none;
  cursor: pointer;
  transition: 0.5s;

  &:hover {
    background-position: right;
  }
}

.btn-register {
  display: block;
  width: 100%;
  height: 40px;
  margin: 1rem 0;
  color: #ffffff;
  font-size: 16px;
  text-transform: capitalize;
  background: linear-gradient(to right, var(--el-color-success-light-5), var(--el-color-success), var(--el-color-success-light-5));
  background-size: 200%;
  border: none;
  border-radius: 4px;
  outline: none;
  cursor: pointer;
  transition: 0.5s;

  &:hover {
    background-position: right;
  }
}

.btn-recover {
  display: block;
  width: 100%;
  height: 40px;
  margin: 1rem 0;
  color: #ffffff;
  font-size: 16px;
  text-transform: capitalize;
  background: linear-gradient(to right, var(--el-color-warning-light-5), var(--el-color-warning), var(--el-color-warning-light-5));
  background-size: 200%;
  border: none;
  border-radius: 4px;
  outline: none;
  cursor: pointer;
  transition: 0.5s;

  &:hover {
    background-position: right;
  }
}
</style>
<style lang="scss">
.recover-notification {
  margin-top: 5px;

  .item-line {
    line-height: 28px;
  }

  p {
    margin-top: 5px;
    color: var(--el-text-color-disabled);
    font-size: 12px;
    line-height: 1.5;
  }
}
</style>
